package org.basis.netty.c3;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

/**
 * eventloop服务端测试，细分EventLoopGroup的工作
 *
 * @author Mr_wenpan@163.com 2021/09/17 11:10
 */
@Slf4j
public class EventLoopServer {

    public static void main(String[] args) {

        // bossGroup组里的nio线程只负责accept事件
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        // wokerGroup里的selectors只负责读写
        NioEventLoopGroup wokerGroup = new NioEventLoopGroup(2);

        // 用户处理handler里的普通事件的EventLoopGroup
        DefaultEventLoopGroup normalWorkers = new DefaultEventLoopGroup(5);

        // 启动器
        ServerBootstrap bootstrap = new ServerBootstrap();

        // 工作细分：bossGroup组里的nio线程只负责accept事件，wokerGroup里的selectors只负责读写
        bootstrap.group(bossGroup, wokerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {

                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast("handler-1", new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf buf = (ByteBuf) msg;
                                log.info(buf.toString(Charset.defaultCharset()));
                                // 让消息传递给下一个handler【如果要传递消息，则必须要调这个】
                                ctx.fireChannelRead(msg);
                            }
                            // 在handler-1后面添加handler-2，并且在handler-2中的任务是由DefaultEventLoopGroup中的线程处理的
                        }).addLast(normalWorkers, "handler-2", new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf buf = (ByteBuf) msg;
                                // 模拟这里处理需要耗时很长的场景，所以需要单独的group线程池来处理
                                TimeUnit.SECONDS.sleep(2);
                                log.info(buf.toString(Charset.defaultCharset()));
                            }
                        });
                    }

                })
                .bind(8080);
    }
}
